import { CustomColumnGroup } from './model/CustomColumnGroup.ts'
import { sequelize } from './model/sequelize.ts'
import { getFieldsJSONFile, resolve } from './utils.ts'

const PROJECT_TYPE_LIST = [
  {
    projectType: 1,
    projectName: '小说'
  },
  {
    projectType: 2,
    projectName: '短剧'
  },
  {
    projectType: 3,
    projectName: '电商'
  }
]

/**
 * 获取远程数据库中所有的自定义列
 * @returns {Array}
 */
const fetchRemoteColumnNameList = async ({ projectType }: { projectType: number }) => {
  const res =  await CustomColumnGroup.findAll({
    where: {
      data_type: 1,
      project_type: projectType
    },
    attributes: ['group_type'],
  })
  return res.map(item => item.dataValues.group_type)
}

/**
 * 过滤出需要增量更新的数据
 * @param {Array} params 参数
 * @param {Array} params.columns 待插入的columns数据
 * @returns 
 */
const filterIncrementData = async({ columns, projectType }) => {
  const columnNameList = await fetchRemoteColumnNameList({ projectType })
  // 过滤出需要插入的数据
  return columns.filter(item => !columnNameList.includes(item.column))
}

async function generateColumns({ columns, projectType }) {
  const needGenerateColumns = await filterIncrementData({ columns, projectType })
  if (needGenerateColumns.length === 0) {
    console.log('不存在需要增量插入的数据，请检查JSON文件是否更新');
    // 关闭连接
    sequelize.close()
    return
  }
  const tasks = needGenerateColumns.map((item) => {
    return CustomColumnGroup.create(
      {
        teamid: 0,
        platform_type: 1,
        project_type: projectType,
        projectid: 0,
        user_id: 0,
        data_type: item.dataType,
        group_name: item.columnType,
        group_type: item.column,
        group_data: item.groupData,
        is_using: 0,
        create_time: Math.floor(Date.now() / 1000),
        update_time: Math.floor(Date.now() / 1000),
        creator: 0,
        updator: 0
      }
    ).then(() => {
      console.log(`projectType: ${projectType}, ${item.columnType}: ${item.column}, dataType: ${item.dataType} 插入成功`);
    }).catch(err => {
      console.log('插入数据失败', err);
    })
  })

  const res = await Promise.all(tasks)

  const taskNum = res.length

  console.log(`\n插入数据完毕, 共插入了${taskNum}个自定义位置数据`);

  // 关闭连接
  sequelize.close()
}

const columnsData = getFieldsJSONFile(resolve('../dist/fields'))


// 生成自定义列
PROJECT_TYPE_LIST.forEach(item => {
  generateColumns({ columns: columnsData, projectType: item.projectType })
})